﻿using Furion;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using YFurion;
using YFurion.Consul;

namespace UpperComputer.Web.Core
{
    [DependsOn(typeof(YFurionApplicationComponent))]
    public class UpperComputerWebCoreApplicationComponent : IApplicationComponent
    {
        public void Load(IApplicationBuilder app, IWebHostEnvironment env, ComponentContext componentContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            // 配置多语言，必须在 路由注册之前
            app.UseAppLocalization();

            app.UseStaticFiles();

            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            IConfiguration serviceEntityConfiguration = App.Configuration.GetSection("ServiceEntity");
            bool enabled = Convert.ToBoolean(serviceEntityConfiguration["Enabled"]);
            if (enabled)
            {
                ServiceEntity serviceEntity = new ServiceEntity
                {
                    Name = serviceEntityConfiguration["Name"],
                    ConsulUrl = serviceEntityConfiguration["ConsulUrl"],
                    IP = serviceEntityConfiguration["IP"],
                    Port = serviceEntityConfiguration.GetValue<int>("Port")
                };
                app.UseConsulClient(App.GetService<IHostApplicationLifetime>() , serviceEntity);
            }
        }
    }
}
